package a4y17Work;

import java.util.Scanner;

public class DecimalConverter {
    // 顺序栈实现
    private static class SeqStack {
        private int[] data;
        private int top;

        public SeqStack(int size) {
            data = new int[size];
            top = -1;
        }

        public boolean isEmpty() {
            return top == -1;
        }

        public void push(int value) {
            data[++top] = value;
        }

        public int pop() {
            return data[top--];
        }
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("请输入一个十进制数字：");
        int decimal = scanner.nextInt();

        System.out.print("请输入想要转换为几进制的数字(2,8,16)：");
        int base = scanner.nextInt();

        if (base != 2 && base != 8 && base != 16) {
            System.out.println("只支持转换为2、8或16进制！");
            return;
        }

        if (decimal < 0) {
            System.out.println("请输入非负十进制整数！");
            return;
        }

        // 特殊情况处理：0的任何进制都是0
        if (decimal == 0) {
            System.out.println("转换结果：0");
            return;
        }

        // 创建栈，大小足够存储转换后的位数
        SeqStack stack = new SeqStack(32);

        // 进制转换
        int num = decimal;
        while (num > 0) {
            int remainder = num % base;
            stack.push(remainder);
            num = num / base;
        }

        // 输出结果
        System.out.print("转换结果：");
        while (!stack.isEmpty()) {
            int digit = stack.pop();
            if (digit < 10) {
                System.out.print(digit);
            } else {
                // 10以上用字母表示，A=10, B=11, ..., F=15
                System.out.print((char)('A' + digit - 10));
            }
        }
        System.out.println();
    }
}